package com.originskyseed.platform.user.controller;

import java.math.BigDecimal;
import java.util.*;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.originskyseed.platform.core.aspect.annotation.RequiredParams;
import com.originskyseed.platform.core.base.BaseController;
import com.originskyseed.platform.core.base.BaseLocaleResource;
import com.originskyseed.platform.core.base.BasePage;
import com.originskyseed.platform.core.base.BaseResponseBody;
import com.originskyseed.platform.core.common.code.CommonResponseCode;
import com.originskyseed.platform.core.filter.helper.SingleSignOnTokenHelper;
import com.originskyseed.platform.user.i18n.UserResponseMsg;
import com.originskyseed.platform.user.model.AnchorProfitVO;
import com.originskyseed.platform.user.model.AnchorRelateLive;
import com.originskyseed.platform.user.model.Dept;
import com.originskyseed.platform.user.model.UserInfo;
import com.originskyseed.platform.user.service.IAnchorRelateLiveService;
import com.originskyseed.platform.user.service.IDeptService;
import com.originskyseed.platform.user.service.IPlayerRelateConsumeService;
import com.originskyseed.platform.user.service.IPlayerRelateViewLiveService;
import com.originskyseed.platform.user.service.IUserInfoService;
import com.originskyseed.platform.user.vo.request.AnchorRelateLiveRequestVO;


/**
 * 主播直播信息表Controller类（OSI_ANCHOR_RELATE_LIVE）
 * 
 * @author Tangwanghui
 */
@Controller
@RequestMapping("/anchorRelateLive")
@BaseLocaleResource(localeFileName = "i18n_user")
public class AnchorRelateLiveController extends BaseController {

	private static final Logger logger = LoggerFactory.getLogger(AnchorRelateLiveController.class);

	@DubboReference
	private IAnchorRelateLiveService anchorRelateLiveService;

	@DubboReference
	private IPlayerRelateConsumeService playerRelateConsumeService;

	@DubboReference
	private IPlayerRelateViewLiveService playerRelateViewLiveService;

	@DubboReference
	private IDeptService deptService;

	@DubboReference
	private IUserInfoService userInfoService;

	/**
	 * 分页查询
	 * 
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/anchorRelateLiveList.json", method = RequestMethod.POST)
	@RequiredParams(names = { "pageNo", "pageSize" })
	public BaseResponseBody<BasePage<AnchorRelateLive>> anchorRelateLiveList(HttpServletRequest request) {
		BaseResponseBody<BasePage<AnchorRelateLive>> result = null;
		try {
			// 请求对象
			AnchorRelateLiveRequestVO requestVO = this.getParameterBean(AnchorRelateLiveRequestVO.class);

			// 分页查询
			BasePage<AnchorRelateLive> page = new BasePage<AnchorRelateLive>(requestVO.getPageNo(), requestVO.getPageSize());
			page = this.anchorRelateLiveService.selectListByPage(requestVO.toMap(), page);
			result = new BaseResponseBody<BasePage<AnchorRelateLive>>(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_LIST_SUCCESS.getMsg()), page);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody<BasePage<AnchorRelateLive>>(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_LIST_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 保存信息
	 * 
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/anchorRelateLiveSave.json", method = RequestMethod.POST)
	@RequiredParams(names = {})
	public BaseResponseBody<AnchorRelateLive> anchorRelateLiveSave(HttpServletRequest request) {
		BaseResponseBody<AnchorRelateLive> result = null;
		try {
			// 请求对象
			AnchorRelateLive anchorRelateLive = this.getParameterBean(AnchorRelateLive.class);

			if (StringUtils.isNotBlank(anchorRelateLive.getId())) {
				this.anchorRelateLiveService.updateByPrimaryKey(anchorRelateLive);
			} else {
				this.anchorRelateLiveService.insertSelective(anchorRelateLive);
			}
			result = new BaseResponseBody<AnchorRelateLive>(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_SAVE_SUCCESS.getMsg()), anchorRelateLive);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody<AnchorRelateLive>(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_SAVE_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 删除信息
	 * 
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/anchorRelateLiveDelete.json", method = RequestMethod.POST)
	@RequiredParams(names = { "ids" })
	public BaseResponseBody<Boolean> anchorRelateLiveDelete(HttpServletRequest request) {
		BaseResponseBody<Boolean> result = null;
		try {
			// 请求参数
			String[] ids = this.getParameterArray("ids", new String[] {});

			this.anchorRelateLiveService.deleteByPrimaryKeys(Arrays.asList(ids));
			result = new BaseResponseBody<Boolean>(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_DELETE_SUCCESS.getMsg()), true);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody<Boolean>(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_DELETE_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 分页查询主播收益
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/selectAnchorProfit.json", method = RequestMethod.POST)
	@RequiredParams(names = { "pageNo", "pageSize" })
	public BaseResponseBody selectAnchorProfit(HttpServletRequest request) throws Exception{
		BaseResponseBody result = null;
		try {
			// 请求对象
			AnchorRelateLiveRequestVO requestVO = this.getParameterBean(AnchorRelateLiveRequestVO.class);

			// 分页查询
			BasePage<AnchorProfitVO> page = new BasePage<AnchorProfitVO>(requestVO.getPageNo(), requestVO.getPageSize());

			// 获取当前登录用户,获取改用户部门下所有的主播
			UserInfo userInfo = SingleSignOnTokenHelper.getCurrentUserInfo(UserInfo.class);

			List<String> anchorIds = new ArrayList<>();

			if (userInfo!=null&&userInfo.getType() == 11) {
				if (userInfo.getOtherAccount() != null && StringUtils.isNotBlank(userInfo.getOtherAccount())) {
					anchorIds.add(userInfo.getOtherAccount());
				}
			} else {
				Dept dept = this.deptService.selectByPrimaryKey(userInfo.getDeptId());
				if (dept != null) {
					// 获取部门下所有主播id
					List<String> deptIds = new ArrayList<>();
					deptIds.add(dept.getId());
					this.selectSonId(dept.getCode(), deptIds);
					anchorIds = this.userInfoService.selectAnchorOtherIdsByDeptIds(deptIds);
				}
			}

			if (anchorIds.size() > 0) {
				requestVO.setList(anchorIds);
				page = this.anchorRelateLiveService.selectAnchorProfitByPage(requestVO.toMap(), page);
				Map<String, Object> queryMap = new HashMap<>();
				queryMap.put("startTime", requestVO.getStartTime());
				queryMap.put("endTime", requestVO.getEndTime());
				for (AnchorProfitVO anchorProfitVO : page.getResults()) {
					queryMap.put("anchorId", anchorProfitVO.getAnchorId());
					queryMap.put("type", 1);
					BigDecimal personalAmount = this.playerRelateConsumeService.selectTotalAmountByMap(queryMap);
					queryMap.put("type", 2);
					BigDecimal rowWheatAmount = this.playerRelateConsumeService.selectTotalAmountByMap(queryMap);
					anchorProfitVO.setPersonalAmount(personalAmount);
					anchorProfitVO.setRowWheatAmount(rowWheatAmount);
					anchorProfitVO.setAmount(personalAmount.add(rowWheatAmount));
					anchorProfitVO.setTotalDuration(getDate(anchorProfitVO.getTotalDurationSecond()*1000));
					anchorProfitVO.setPersonalDuration(getDate(anchorProfitVO.getPersonalDurationSecond()*1000));
					anchorProfitVO.setRowWheatDuration(getDate(anchorProfitVO.getRowWheatDurationSecond()*1000));
					anchorProfitVO.setFamilyIncome(anchorProfitVO.getAmount().multiply(new BigDecimal(0.5)));

					Integer validDay = this.anchorRelateLiveService.selectValidDay(queryMap);
					anchorProfitVO.setEffectiveDays(validDay);
				}
			}
			result = new BaseResponseBody(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_LIST_SUCCESS.getMsg()), page);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_LIST_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 查询主播总收益
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/selectTotalRevenue.json", method = RequestMethod.POST)
	public BaseResponseBody selectTotalRevenue(HttpServletRequest request) {
		BaseResponseBody result = null;
		try {
			// 请求对象
			AnchorRelateLiveRequestVO requestVO = this.getParameterBean(AnchorRelateLiveRequestVO.class);
			// 总额
			BigDecimal amount = BigDecimal.ZERO;
			// 获取当前登录用户,获取改用户部门下所有的主播
			UserInfo userInfo = SingleSignOnTokenHelper.getCurrentUserInfo(UserInfo.class);
			List<String> anchorIds = new ArrayList<>();
			if (userInfo != null && userInfo.getType() == 11) {
				if (userInfo.getOtherAccount() != null && StringUtils.isNotBlank(userInfo.getOtherAccount())) {
					anchorIds.add(userInfo.getOtherAccount());
				}
			} else {
				Dept dept = this.deptService.selectByPrimaryKey(userInfo.getDeptId());
				if (dept != null) {
					// 获取部门下所有主播id
					List<String> deptIds = new ArrayList<>();
					deptIds.add(dept.getId());
					this.selectSonId(dept.getCode(), deptIds);
					anchorIds = this.userInfoService.selectAnchorOtherIdsByDeptIds(deptIds);
				}
			}

			if (anchorIds.size() > 0) {
				Map<String, Object> queryMap = new HashMap<>();
				queryMap.put("startTime", requestVO.getStartTime());
				queryMap.put("endTime", requestVO.getEndTime());
				queryMap.put("list", anchorIds);
				amount = this.playerRelateConsumeService.selectTotalAmountByMap(queryMap);
			}

			Map<String, Object> map = new HashMap<>();
			map.put("amount", amount);
			map.put("familyIncome", amount.multiply(new BigDecimal(0.5)));
			result = new BaseResponseBody(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_LIST_SUCCESS.getMsg()), map);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_LIST_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 分页查询主播收益
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/selectProfit.json", method = RequestMethod.POST)
	@RequiredParams(names = { "pageNo", "pageSize" })
	public BaseResponseBody selectProfit(HttpServletRequest request) throws Exception{
		BaseResponseBody result = null;
		try {
			// 请求对象
			AnchorRelateLiveRequestVO requestVO = this.getParameterBean(AnchorRelateLiveRequestVO.class);
			Integer type = this.getParameterInteger("type", null);

			// 分页查询
			BasePage<AnchorRelateLive> page = new BasePage<AnchorRelateLive>(requestVO.getPageNo(), requestVO.getPageSize());
			// 获取当前登录用户,获取改用户部门下所有的主播
			UserInfo userInfo = SingleSignOnTokenHelper.getCurrentUserInfo(UserInfo.class);
			List<String> anchorIds = new ArrayList<>();
			if(userInfo.getType()==11)
			{
				if(userInfo.getOtherAccount()!=null&&StringUtils.isNotBlank(userInfo.getOtherAccount())) {
					anchorIds.add(userInfo.getOtherAccount());
				}
			}
			else {
				Dept dept = this.deptService.selectByPrimaryKey(userInfo.getDeptId());
				if (dept != null) {
					// 获取部门下所有主播id
					List<String> deptIds = new ArrayList<>();
					deptIds.add(dept.getId());
					this.selectSonId(dept.getCode(), deptIds);
					anchorIds = this.userInfoService.selectAnchorOtherIdsByDeptIds(deptIds);
				}
			}

			// 主播id不为空则查询
			if (anchorIds.size() > 0) {
				requestVO.setList(anchorIds);
				page = this.anchorRelateLiveService.selectListByPage(requestVO.toMap(), page);
				Map<String, Object> queryMap = new HashMap<>();
				for (AnchorRelateLive anchorRelateLive : page.getResults()) {
					queryMap.put("startDate", anchorRelateLive.getStartTime());
					queryMap.put("endDate", anchorRelateLive.getEndTime());
					queryMap.put("anchorId", anchorRelateLive.getAnchorId());
					queryMap.put("type", 1);
					BigDecimal personalAmount = this.playerRelateConsumeService.selectTotalAmountByMap(queryMap);
					queryMap.put("type", 2);
					BigDecimal rowWheatAmount = this.playerRelateConsumeService.selectTotalAmountByMap(queryMap);
					anchorRelateLive.setPersonalAmount(personalAmount);
					anchorRelateLive.setRowWheatAmount(rowWheatAmount);
					anchorRelateLive.setAmount(personalAmount.add(rowWheatAmount));
					if (anchorRelateLive.getEndTime() != null) {
						anchorRelateLive.setTotalDuration(getDate(anchorRelateLive.getEndTime().getTime() - anchorRelateLive.getStartTime().getTime()));
					}
					Integer watchNumber = this.playerRelateViewLiveService.selectWatchNumber(queryMap);
					anchorRelateLive.setWatchNumber(watchNumber);
				}
			}

			result = new BaseResponseBody(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_LIST_SUCCESS.getMsg()), page);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_LIST_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}


	private static String getDate(long diff) {
		StringBuffer sb = new StringBuffer();
		if(diff<=0)
		{
			sb.append(0+"秒");
			return sb.toString();
		}
		long days =diff  / (1000 * 60 * 60 * 24);
		if(days>0)
		{
			sb.append(days+"天");
		}
		long hours = (diff -days*(1000 * 60 * 60 * 24))/(1000* 60 * 60); //获取时
		if(hours>0)
		{
			sb.append(hours+"小时");
		}
		long minutes = (diff -days*(1000 * 60 * 60 * 24)-hours*(1000* 60 * 60))/(1000* 60);  //获取分钟
		if(minutes>0)
		{
			sb.append(minutes+"分");
		}
		long seconds=(diff/1000-days*24*60*60-hours*60*60-minutes*60);//获取秒
		if(seconds>0)
		{
			sb.append(seconds+"秒");
		}

		return sb.toString();
	}

	/**
	 * 查询组织架构接口
	 * 
	 * @param code
	 * @param list
	 * @throws Exception
	 */
	private void selectSonId(String code, List<String> list) throws Exception {
		List<Dept> deptList = this.deptService.selectByParentCode(code);
		if (deptList != null) {
			for (Dept dept1 : deptList) {
				list.add(dept1.getId());
				selectSonId(dept1.getCode(), list);
			}
		}
	}
}